package com.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;

public class SimpleHttpClient {
	public static void main(String[] args){
		//用法
		if(args.length<1){
			System.err.println("Usage:SimpleHttpClient <url>");
			return;
		}
		
		//解析
		try {
			URL url=new URL(args[0]);
			String host=url.getHost();
			String path=url.getPath();
			int port=url.getPort();
			if(port<0) port=0;
			//发送请求
			String request="GET " + path+ " HTTP/1.1\n";
			request+="host: " + host;
			request+="\n";
			Socket sock=new Socket(host, port);
			PrintWriter writer=new PrintWriter(sock.getOutputStream());
			writer.println(request);
			writer.flush();
			//读取并输出响应
			BufferedReader reader=new BufferedReader(new InputStreamReader(sock.getInputStream()));
			String next_record=null;
			while((next_record=reader.readLine())!=null){
				System.out.println(next_record);
			}
			sock.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
